<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :width="width"
    :close-on-click-modal="false"
    :before-close="handleCancel"
  >
    <el-form :ref="refName" label-position="top" :model="model" :rules="rules" class="updateForm">
      <el-form-item label="对比时间:" prop="monthScope">
        <el-date-picker v-model="model.monthScope" type="monthrange" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份" style="width: 100%" @change="monthScopeChange" />
      </el-form-item>
      <!-- <el-form-item label="对比区域:" prop="regionNo">
        <region v-model="model.regionNo" :code="indexParams.regionCode" :value.sync="model.regionNo" />
      </el-form-item> -->
      <el-form-item label="上传对比文件:" prop="column2">
        <el-upload
          ref="upload"
          drag
          action=""
          :auto-upload="false"
          :show-file-list="true"
          :multiple="false"
          :limit="1"
          :on-change="fileChange"
          :on-remove="fileRemove"
          :file-list="fileList"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>
      <p class="tip" style="font-weight: 500">注意：</p>
      <span class="tip">1.仅可上传固定的Excel模板，如需导入模板，可<span class="clickDown" @click="clickDown">点击下载</span>《比对表》</span>
      <p class="tip">2.若不上传比对文件，则直接和老人异动表中数据进行比对</p>
    </el-form>
    <span slot="footer">
      <el-button @click="modelClose">取 消</el-button>
      <el-button type="primary" :loading="disableSubmit" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { postAction } from '@/api/manage'
import axios from 'axios'
// import region from './regionCustom'

export default {
  components: {
  },
  data() {
    return {
      model: {},
      formData: null,
      refName: 'ruleForm',
      visible: false,
      disableSubmit: false,
      updateState: '',
      title: '数据比对',
      width: '520px',
      fileList: [],
      baseURL: `${process.env.VUE_APP_BASE_API}`,
      regionlist: [],
      indexParams: {},
      btnisShow: false,
      exportTimer: null,
      rules: {
        monthScope: [{ required: true, message: '请选择', trigger: 'change' }],
        regionNo: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      url: {
        update: '/venerableAge/release/omissionCompare'
      }
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    fileChange(file, fileList) {
      this.fileList = fileList.slice(-1) // 保留最新一个
    },
    fileRemove() {
      this.fileList = []
    },
    monthScopeChange(e) {
      if (e && e.length === 2) {
        this.model.startMonth = this.$moment(e[0]).format('YYYY-MM')
        this.model.endMonth = this.$moment(e[1]).format('YYYY-MM')
      }
    },
    onSuccess() {},
    handlePreview(file) {
      window.open(file.url || file.response.data, '_blank')
    },
    add(indexParams) {
      this.indexParams = indexParams
      if (indexParams.type === 1) {
        this.title = '漏发数据比对'
      } else if (indexParams.type === 2) {
        this.title = '多发数据比对'
      }
      this.updateState = 'add'
      this.visible = true
      this.model = {
        type: indexParams.type
      }
      // this.getAreaList()
      this.$nextTick(() => {
        this.$refs[this.refName]?.clearValidate()
      })
    },
    getAreaList() {
      const param = {
        pageNum: 1,
        pageSize: 10000,
        startTime: this.indexParams.startTime,
        endTime: this.indexParams.endTime
      }
      this.$store.dispatch('app/setLoading', true)
      postAction('/venerableAge/release/getReleaseRegion', param).then((res) => {
        if (res.status === 0) {
          const data = res.data || {}
          this.regionlist = this.flattenRegionData(data)
        } else {
          this.$message.warning(res.message || '操作失败！')
        }
      }).finally(() => {
        this.$store.dispatch('app/setLoading', false)
      })
    },
    flattenRegionData(data) {
      const topItem = {
        regionNo: data.regionNo,
        regionName: data.regionName
      }
      // 合并顶层对象和 itemRespList 中的所有项
      return [topItem, ...(data.itemRespList || [])]
    },
    submitForm() {
      if (this.disableSubmit) return // 防止重复点击
      this.$refs[this.refName].validate((valid) => {
        if (valid) {
          this.disableSubmit = true // ✅ 开启禁用
          // ✅ 每次都创建新的 FormData
          const submitData = new FormData()
          // ✅ 先添加文件（如果有）
          if (this.fileList.length > 0) {
            submitData.append('file', this.fileList[0].raw) // raw 是 File 对象
          }
          // ✅ 再添加 model 的其他字段
          Object.keys(this.model).forEach(key => {
            if (key !== 'monthScope' &&
                this.model[key] !== null &&
                this.model[key] !== undefined &&
                this.model[key] !== '') {
              submitData.append(key, this.model[key])
            }
          })
          let fileName = ''
          if (this.indexParams.type === 1) {
            fileName = '漏发数据对比表'
          } else if (this.indexParams.type === 2) {
            fileName = '多发数据对比表'
          }
          const token = this.$getXmStorage('XM_COLOR')
          const head = { 'Authorization': `Bearer ${token}`, 'Content-Type': 'multipart/form-data' }
          this.$store.dispatch('app/setLoading', true)
          axios({
            url: this.baseURL + this.url.update,
            method: 'post',
            responseType: 'blob',
            data: submitData,
            headers: head
          }).then(res => {
            const data = res.data
            if (!data) {
              this.$message.warning('文件下载失败')
              return
            }
            if (data.type === 'application/json') { // 接口返回的数据类型如果是json，说明是报错信息
              const reader = new FileReader()
              reader.readAsText(data, 'utf-8')// 这时候你的msg字段是blob类型的，不能直接用，所以数据类型要先转回来
              reader.onload = () => { // 这里是处理异步，其他方式用不了，这里很关键
                const { message } = JSON.parse(reader.result)// 转回来是json类型，再转一次
                this.$message.warning(message) // 弹出错误提示
              }
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
            } else {
              const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
              const link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName + '.xlsx')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) // 下载完成移除元素
              window.URL.revokeObjectURL(url) // 释放掉blob对象
            }
          }).finally(() => {
            this.$store.dispatch('app/setLoading', false)
            this.disableSubmit = false // ✅ 恢复按钮
          })
        } else {
          return false
        }
      })
    },
    modelClose() {
      this.visible = false
      this.$refs.upload.clearFiles()
      this.formData = null
      this.fileList = []
    },
    // 定时器
    intervalShowButton() {
      this.exportTimer = setTimeout(() => {
        this.btnisShow = false
      }, this.timeNum)
    },
    clickDown() {
      this.btnisShow = true
      // 调用倒计时方法
      this.intervalShowButton()
      const fileName = '对比模版'
      const token = this.$getXmStorage('XM_COLOR')
      const head = { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
      axios({
        method: 'post',
        url: this.baseURL + '/venerableAge/release/exportCompareTemplate',
        responseType: 'blob',
        data: {},
        headers: head
      }).then(res => {
        const data = res.data
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (data.type === 'application/json') { // 接口返回的数据类型如果是json，说明是报错信息
          const reader = new FileReader()
          reader.readAsText(data, 'utf-8')// 这时候你的msg字段是blob类型的，不能直接用，所以数据类型要先转回来
          reader.onload = () => { // 这里是处理异步，其他方式用不了，这里很关键
            const { message } = JSON.parse(reader.result)// 转回来是json类型，再转一次
            this.$message.warning(message) // 弹出错误提示
          }
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      }).catch(res => {
        this.$message.error(res.message || '系统异常')
        this.btnisShow = false
        if (this.exportTimer) {
          clearTimeout(this.exportTimer) // 清除我们的定时器
        }
      })
    },
    handleCancel(done) {
      done()
    }
  }
}
</script>

<style lang="scss" scoped>
.updateForm{
  padding: 0 30px;
  ::v-deep .el-form-item__label{
    line-height: 16px;
  }
  .el-select, .el-cascader{
    width: 100%;
  }
  .clickDown{
    cursor: pointer;
    color: var(--subjectColor);
  }
}
</style>
